import math
import random
import subprocess as sp
#from domination import *
#options = {'blue': 'theta_agent_moving_group', 'level': 'clover2', 'record': False, 'replay': False, \
#'invisible': False, 'output': 'evolutionRes', 'red': 'theta_agent_moving_group_edit'}
old_hd = 40
old_wbp = 100
new_hd = old_hd
new_wbp = old_wbp

run = 1
f = open('running.evo', 'w')
f.write(str(run)+'\n')
f.close()

while(run == 1):
    
    if random.random() > (1/2):
        new_hd = random.randint(1,50)
        if random.random() > (1/3):
            new_wbp = random.randint(50,150)
    else:
        new_wbp = random.randint(1,50)
        if random.random() > (1/3):
            new_hd = random.randint(50,150)
    
    f = open('params_old','w')
    f.write(str(old_hd)+'\n'+str(old_wbp)+'\n')
    f.close()
    f = open('params_new','w')
    f.write(str(new_hd)+'\n'+str(new_wbp)+'\n')
    f.close()
    
    iter = 23
    score = {'Red':[], 'Blue':[]}
    winsRed = 0
    avgRed = 0
    avgBlue = 0

    for i in range(iter):
        #game = Domination(options)
        #res = game.game_loop()
        
        #YO DAWG, I HERD YOU LIKE PYTHON...
        p = sp.Popen('python domination.py -b theta_agent_moving_group -r theta_agent_moving_group_edit -l clover2 -o outputEvo', shell=True)
        p.wait()
        f = open('outputEvo', 'r')
        res = {}
        for l in f.readlines():
            r = l.split(': ')
            if len(r) > 1:
               res[r[0]] = int(r[1])
        f.close()
        if res['Red'] > res['Blue']:
            winsRed += 1
        avgRed += float(res['Red'])/iter
        avgBlue += float(res['Blue'])/iter
        for k in res:
            score[k].append(res[k])

    print 'Red wins',winsRed
    print 'Red',avgRed,'Blue',avgBlue
    
    f = open('evolutionResults.txt', 'a')
    f.write('Red wins:'+str(winsRed)+'\n')
    f.write('Red:'+str(avgRed)+' Blue:'+str(avgBlue)+'\n')
    f.write('\n')
    f.close()
    
    if winsRed > (iter/2) and avgRed > avgBlue:
        old_hd = new_hd
        old_wbp = new_wbp
    else:
        new_hd = old_hd
        new_wbp = old_wbp
    
    f = open('running.evo', 'r')
    run = int(f.readline())
    f.close()
    
    #stdRed = 0
    #stdBlue = 0
    #for i in range(iter):
    #    stdRed = float((score['Red'][i] - avgRed) ** 2)/iter
    #    stdBlue = float((score['Blue'][i] - avgBlue) ** 2)/iter
    #print 'Red',math.sqrt(stdRed),'Blue',math.sqrt(stdBlue)
